from goods.models import GoodsChannelGroup
from django.core.cache import cache

def get_categories():
    # 定义一个空字典, 来存放分类数据
    data = cache.get('categories')

    if not data:
        data = {}
        # 获取了所有的频道组
        channels_group_all = GoodsChannelGroup.objects.all()

        for channel_group in channels_group_all:
            channel_group_data = {
                "channels": [],
                "sub_cats": []
            }

            data[channel_group.id] = channel_group_data

            for channel in channel_group.goodschannel_set.all():
                cat1 = channel.category  # 找到渠道对应的一级分类
                channel_data = {"id": channel.id, "name": cat1.name, "url": channel.url}
                channel_group_data['channels'].append(channel_data)

                for cat2 in cat1.subs.all():
                    cat2_data = {
                        "id": cat2.id,
                        "name": cat2.name,
                        "sub_cats": []
                    }
                    channel_group_data['sub_cats'].append(cat2_data)

                    for cat3 in cat2.subs.all():
                        cat3_data = {"id": cat3.id, "name": cat3.name}
                        cat2_data['sub_cats'].append(cat3_data)

        cache.set('categories', data ,3600)

    return data
